package jatosoft.accounting.webapp.managedbean;

import jatosoft.accounting.dao.model.BaseModel;
import jatosoft.accounting.webapp.UIModel;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public abstract class BaseManagedBean {

	protected String userId;
	protected Log logger = LogFactory.getLog(this.getClass());

	List<UIModel> uiModels;

	public BaseManagedBean() {
		super();
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public FacesContext getFacesContext() {
		return FacesContext.getCurrentInstance();
	}

	public void addMessage(String msg) {
		getFacesContext().addMessage(null, new FacesMessage(msg));
	}

	public abstract void initPage();

	public List<UIModel> getUiModels() {
		return uiModels;
	}

	public void setUiModels(List<UIModel> uiModels) {
		this.uiModels = uiModels;
	}

	void dumpModel2UIModel(List<? extends BaseModel> models) {
		uiModels = new ArrayList<UIModel>();

		for (BaseModel m : models) {
			UIModel um = new UIModel(m);
			uiModels.add(um);
		}

	}

	public void updateModel(ValueChangeEvent vEvent) {
		Integer id = (Integer) ((UIInput) vEvent.getComponent().getParent()
				.findComponent("hidVoucherId")).getValue();
		if (id != null) {
			for (UIModel uim : uiModels) {
				if (id.equals((uim.getModel()).getId())) {
					uim.setSelected((Boolean) vEvent.getNewValue());
					break;
				}
			}
		}
		((UIInput) vEvent.getComponent()).setLocalValueSet(false);
	}

	public BaseModel getSelectModel() {
		BaseModel bModel = null;
		for (UIModel uiM : uiModels) {
			if (uiM.getSelected()) {
				bModel = uiM.getModel();
				break;
			}
		}
		return bModel;

	}
	
	public List<BaseModel> getSelectModels() {
		List<BaseModel> baseModels = new ArrayList<BaseModel>();
//		BaseModel bModel = null;
		for (UIModel uiM : uiModels) {
			if (uiM.getSelected()) {
//				bModel = uiM.getModel();
				baseModels.add(uiM.getModel());
			}
		}
		return baseModels;

	}

	public String getLoginUserId() {
		String id;
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			id = ((UserDetails) principal).getUsername();
		} else {
			id = principal.toString();
		}
		return id;
	}

	public Integer getLinkModelId() {
		return Integer.parseInt(getFacesContext().getExternalContext()
				.getRequestParameterMap().get("linkModelId"));
	}


}